import sys
import time
# from DBUtils.PersistentDB import PersistentDB
sys.path.append('/data/snmonitor')
# sys.path.append('E:\\snmonitor')
## 导入自定义的包
from src.core.monitorApplication import ServiceInformation
from src.core.controllerBase import msyqlInfo

def insertData():
    while True:
        try:
            time.sleep(2)
            # info = info
            # print(info)
            # obtain monitor info 监控信息获取
            hostname = ServiceInformation.hostname
            cpu = ServiceInformation.obtain_cpu()
            cpudata = hostname, cpu["cpu_utilization"]
            mem = ServiceInformation.obtain_memory()
            memdata = (hostname, mem["mem_total"], mem["mem_u"], mem["mem_utilization"], mem["mem_free"])
            disk = ServiceInformation.obain_disk()
            diskdata = (hostname, disk["disk_total"], disk["disk_used"], disk["disk_free"], disk["disk_utilization"])

            # Splicing SQL 拼接SQL
            sqlcpu = '''
            INSERT INTO `monitor`.`monitor_cpu`(`hostname`,`cpu_utilization`,`at_time`) VALUES ("%s", "%s", now());
            ''' % cpudata
            sqlmem = '''
            INSERT INTO `monitor`.`monitor_mem`(`hostname`,`mem_total`,`mem_used`,`mem_utilization`,`mem_free`,`at_time`) VALUES ("%s", "%s", "%s", "%s", "%s", now());
            ''' % memdata
            sqldisk = '''
            INSERT INTO `monitor`.`monitor_disk`(`hostname`,`disk_total`,`disk_used`,`disk_free`,`disk_utilization`,`at_time`) VALUES ("%s", "%s", "%s", "%s", "%s", now());
            ''' % diskdata

            # conn = pymysql.connect(host="192.168.7.21", port=3306, user="snwituser", password="XzZH2fAiBSAR", database="monitor", charset="utf8")
            conn = msyqlInfo()
            cursor = conn.cursor()
            cursor.execute(sqlcpu)
            conn.commit()
            print("sqlcpu write success")
            cursor.execute(sqlmem)
            conn.commit()
            print("sqlmem write success")
            cursor.execute(sqldisk)
            conn.commit()
            print("sqldisk write success")
            # 发送命令并返回结果，存储在游标中
            # cursor.execute(sql)
            # 获取多个查询结果集，指定多个对象
            # data = cursor.fetchmany(4)
            # 获取下一个查询结果集，结果集是一个对象
            # one_row = cursor.fetchone()
            # 获取所有查询结果集。结果所有对象
            # data = cursor.fetchall()r
            # cursor.
            # print(data)
            # print(one_row)
            cursor.close()
            conn.close()
        except Exception as e:
            print(e)





if __name__ == "__main__":
    # a = msyqlInfo()
    # print(a)
    mysqlConnect()
